package hnx.ca.xml.verifier;

/*
 *============================================================================
 * Signerlet, the applet for signing documents from web
 * Copyright (c) 2011 VNPT Epay Joint Stock Company
 *============================================================================
 * REFERENCE:
 * http://java.sun.com/developer/technicalArticles/xml/dig_signature_api
 */
import java.security.*;
import java.security.cert.*;
import java.util.*;
import javax.xml.crypto.*;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.keyinfo.*;

/**
 * X509KeySelector in the example in the reference link 
 * @author Dinh Quoc Dat
 * @version 2011.03.2516
 */
public class selector extends KeySelector {

  /**
   * Select a key from somewhere?
   * @param keyInfo
   * @param purpose
   * @param method
   * @param context
   */
  @SuppressWarnings("rawtypes")
public KeySelectorResult select(KeyInfo keyInfo,KeySelector.Purpose purpose,
    AlgorithmMethod method, XMLCryptoContext context)
    throws KeySelectorException {
    
    Iterator ki = keyInfo.getContent().iterator();
    while (ki.hasNext()) {
      XMLStructure info = (XMLStructure) ki.next();
      if (!(info instanceof X509Data))
        continue;
      
      X509Data x509Data = (X509Data) info;
      Iterator xi = x509Data.getContent().iterator();
      while (xi.hasNext()) {
        Object o = xi.next();
        if (!(o instanceof X509Certificate))
          continue;
        
        final PublicKey key = ((X509Certificate) o).getPublicKey();
        
        //make sure the algorithm is compatible with the method
        if (algEquals(method.getAlgorithm(), key.getAlgorithm())) {
          return new KeySelectorResult() {
            public Key getKey() {
              return key;
            }
          };
        }//if
      }//while inner
    }//while outer
    throw new KeySelectorException("No key found!");
  }

  /**
   * Check if 2 algorithms are equal
   * @param algURI
   * @param algName
   * @return 'true' if the 2 algorithms are equal
   */
  public static boolean algEquals(String algURI, String algName) {
    if ((algName.equalsIgnoreCase("DSA") && 
      algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) || 
      (algName.equalsIgnoreCase("RSA") && 
      algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1))) {
      return true;
    } 
    else {
      return false;
    }
  }//algEquals
}